package model

import (
	"bysy-gin/libs/auth"
	"time"
)

/*
create table user
(

	id       int auto_increment
	    primary key,
	username varchar(128)                        not null,
	password varchar(512)                        not null,
	address  varchar(256)                        null,
	email    varchar(128)                        not null,
	add_time timestamp default CURRENT_TIMESTAMP not null,   每次添加数据，把当前时间记录一下
	role     int       default 0                 not null,   定义是普通用户 还是管理员
	enable   int       default 1                 not null    定义用户字段，是否启用该用户

);
*/
type UserModel struct {
	Id       uint64    `gorm:"column:id;primary_key;auto_increment" json:"id"`
	Username string    `gorm:"column:username;not null" json:"username" form:"username" binding:"required"`
	Password string    `gorm:"column:password;not null" json:"password" form:"password" binding:"required"`
	Address  string    `gorm:"column:address; not null" json:"address" form:"address" `
	Email    string    `gorm:"column:email;not null" json:"email" form:"email" binding:"required"`
	AddTime  time.Time `gorm:"column:add_time; default:CURRENT_TIMESTAMP;not null" json:"addtime" form:"addtime" `
	Role     uint64    `gorm:"column:role; default:0;not null" json:"role"`
	Enable   uint64    `gorm:"column:enable; default:1; not null" json:"enable"`
}

func (u *UserModel) TableName() string {
	return "user"
}

// 注册
func (u *UserModel) Create() error {
	return DB.Self.Create(&u).Error
}

// 密码加密
func (u *UserModel) Encryt() (err error) {
	u.Password, err = auth.Encrypt(u.Password)
	return
}

// 设置时间格式
//func (u *UserModel) ModifyTimeFormat() {
//	u.AddTime = u.AddTime.Format("2006-01-02 15:04:05")
//}

// 登录查询
func GetUser(username string) (*UserModel, error) {
	u := &UserModel{}
	r := DB.Self.Where("username = ?", username).First(&u)
	return u, r.Error
}
